<?php
/**
 * Created by PhpStorm.
 * User: sofwu
 * Date: 2019/1/11
 * Time: 下午3:13
 */
namespace App\Http\Controllers\Api\V1;

use App\Http\Transformer\OrderTransformer;
use App\Http\Transformer\UserTransformer;
use App\Model\OauthUser;
use App\Model\Order;
use App\Model\User;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{

    public function __construct()
    {
        $this->middleware('api.auth', ['only' => ['me', 'order']]);
    }

    /**
     * 小程序用户登陆
     */
    public function thirdLogin()
    {
        $rules = [
            'oauth' => ['required'],
            'nickname' => ['required'],
            'head_pic' => ['required'],
            'sex' => ['required'],
        ];

        $payload = app('request')->all();

        $validator = app('validator')->make($payload, $rules);

        if ($validator->fails()) {
            throw new \Dingo\Api\Exception\ResourceException('Could not post miniProgramLogin.', $validator->errors());
        }



        if($payload['oauth'] === 'miniapp'){
            try{
                $app = app('EasyWeChat')->miniProgram();
                $session = $app->auth->session($payload['code']);

                if (isset($session['errcode'])) {
                    throw new \Dingo\Api\Exception\ResourceException('小程序登录失败, errcode : '.$session['errcode'].', errmsg : '.$session['errmsg']);
                }

                $payload['openid'] = $session['openid'];

            }catch (\Exception $e){
                throw new \Dingo\Api\Exception\ResourceException($e->getMessage());
            }
        }


        $user = $this->thirdLoginStore($payload);
        if (!$user){
            $user = new User;
            $user->name = $payload['nickname'];
            $user->nickname = $payload['nickname'];
            $user->head_pic = $payload['head_pic'];
            $user->sex = $payload['sex'];
            $user->save();

            $oauthUser = new OauthUser;
            $oauthUser->openid = $payload['openid'];
            $oauthUser->nick_name = $payload['nickname'];
            $oauthUser->oauth = $payload['oauth'];
            $user->oauthUser()->save($oauthUser);
        }


        if (! $token = auth()->login($user)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }


    /**
     * 第三方用户查询
     * @param $data
     * @return mixed
     */
    public function thirdLoginStore($data)
    {
        if(empty($data['openid'])|| empty($data['oauth'])){
            throw new \Dingo\Api\Exception\ResourceException('参数错误, openid,unionid或oauth为空');
        }


        $oauthUser = OauthUser::where(['oauth'=>$data['oauth'], 'openid'=>$data['openid']])->first();
        if (isset($oauthUser->users)){
            $user = $oauthUser->users;
        }else{
            $user = null;
        }

        return $user;
    }


    /**
     * 获取用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function me(){

        return $this->response->item($this->auth->user(), new UserTransformer);
    }


    /**
     * 我的订单
     * @return \Dingo\Api\Http\Response
     */
    public function order(){
        $user = $this->auth->user();
        $orders = Order::where(['user_id'=>$user->id, 'order_status'=>1, 'pay_status'=>1])->orderBy('id', 'desc')->paginate();
        return $this->response->paginator($orders, new OrderTransformer);
    }


    protected function respondWithToken($token)
    {
        return response()->json(['data'=>[
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]]);
    }
}